package cn.xiaoxiang.basic.service.impl;

import cn.xiaoxiang.basic.config.BussinessException;
import cn.xiaoxiang.basic.constants.LoginKou;
import cn.xiaoxiang.basic.constants.Register;
import cn.xiaoxiang.basic.dto.EmailDto;
import cn.xiaoxiang.basic.dto.SmsCodeDto;
import cn.xiaoxiang.basic.service.VerifyCodeService;
import cn.xiaoxiang.basic.util.StrUtils;
import cn.xiaoxiang.basic.util.VerifyCodeUtils;

import cn.xiaoxiang.user.domain.User;
import cn.xiaoxiang.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements VerifyCodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private  JavaMailSender javaMailSender;
    @Override
    public String graph(String redisKey) {
        String s = StrUtils.getComplexRandomString(4);
        redisTemplate.opsForValue().set(redisKey,s,5, TimeUnit.MINUTES);
        String s1 = VerifyCodeUtils.VerifyCode(100, 35, s);
        return s1;

    }

    @Override
    public void smsCode(SmsCodeDto dto) {
       if("register".equals(dto.getType())){
           //图形验证码
           TuVerification(dto);
           //手机验证码
           Verification(dto,Register.REGISTER_PHONE_KEY);
       } else if("binder".equals(dto.getType())){
            //手机验证码
            Verification(dto, LoginKou.BINDER_PHONE_KEY);
        }


    }

    private void TuVerification(SmsCodeDto dto) {
        //1.参数验证
        if(StringUtils.isBlank(dto.getImageCodeKey())){
            throw new BussinessException("uuid不能为空");
        }
        if(StringUtils.isBlank(dto.getImageCodeValue())){
            throw new BussinessException("图片验证码不能为空");
        }
        //2图形验证码是否正确
        String o = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (StringUtils.isBlank(o)||!dto.getImageCodeValue().equalsIgnoreCase(o)){
            throw new BussinessException("图片验证码有误");
        }
        //3.手机是否注册过
        User user= userMapper.finfByphone(dto.getPhone());
        if(null!=user){
            throw new BussinessException("你已经注册过了");
        }
        //4.两次验证码是否超过60秒
        Long tll = redisTemplate.getExpire(String.format(Register.REGISTER_PHONE_KEY, dto.getPhone()));
        if(null!=tll&&tll>((Register.IMAGE_CODE-1)*60)){
            throw new BussinessException("请超过60秒后发送");
        }
    }

    private void Verification(SmsCodeDto dto,String ridesKey) {
        //5.手机验证码是否过期
        String smsCode="";
        String sm= (String) redisTemplate.opsForValue().get(String.format(ridesKey, dto.getPhone()));
        if(StringUtils.isNotBlank(sm)){
            smsCode=sm;
        }else {
            smsCode= StrUtils.getComplexRandomString(4);
        }
        log.info("手机号验证码为：{}", smsCode);
        //6.保存在resdis 中
        redisTemplate.opsForValue().set(String.format(ridesKey, dto.getPhone()),smsCode,Register.PHONE_SHOUJI,TimeUnit.MINUTES);
        //7.发送短信
    }

    @Override
    public void email(EmailDto emailDto) {
        //1.参数验证
        //2图形验证码是否正确
        String o = (String) redisTemplate.opsForValue().get(emailDto.getImageCodeKey());
        if (StringUtils.isBlank(o) || !emailDto.getImageCodeValue().equalsIgnoreCase(o)) {
            throw new BussinessException("图片验证码有误");
        }
        //3.手机是否注册过
        User user2 = userMapper.finfByemail();
        if (null != user2) {
            throw new BussinessException("你已经注册过了");
        }
        //4.两次验证码是否超过60秒
        Long tll = redisTemplate.getExpire(String.format(Register.REGISTER_PHONE_KEY, emailDto.getEmail()));
        if (null != tll && tll > ((Register.IMAGE_CODE - 1) * 60)) {
            throw new BussinessException("请超过60秒后发送");
        }
        //5.手机验证码是否过期
        String email2 = "";
        String sm = (String) redisTemplate.opsForValue().get(String.format(Register.REGISTER_PHONE_KEY, emailDto.getEmail()));
        if (StringUtils.isNotBlank(sm)) {
            email2 = sm;
        } else {
            email2 = StrUtils.getComplexRandomString(4);
        }
        log.info("手机号验证码为：{}", email2);
        //6.保存在resdis 中
        redisTemplate.opsForValue().set(String.format(Register.REGISTER_PHONE_KEY, emailDto.getEmail()), email2, Register.PHONE_SHOUJI, TimeUnit.MINUTES);
        //7发送邮件
        try {

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("792130298@qq.com");
            helper.setSubject("注册");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText(email2, true);
            // 5.设置收件人
            helper.setTo("792130298@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.info("发送失败，请重新发送", e);

        }
    }

}